<?php
class Model_Manufacturer extends Zend_Db_Table_Abstract{
	protected $_name = 'manufacturer';
	protected $_dependentTables = array("Model_ManCat", "Model_Product");
	
	public function getAllManufacturers(){
		return $this->fetchAll($this->select()->order('priority'));
	}
	public function getManufacturerByID($id){
		return $this->find($id)->current();
	}
	public function getManufacturerByName($name){
		return $this->fetchRow("name = '".$name."'");
	}
	public function createManufacturer($name, $logo, $category_id,$priority, $page_title, $page_description, $tag){
		$man = $this->createRow();
		$man->name = $name;
		$man->logo  = $logo;
		$man->priority = $priority;
		$man->page_title = $page_title;
		$man->page_description = $page_description;
		$man->tag = $tag;
		$man->save();
		$id = $this->_db->lastInsertId();
		if($id){
			$tblManCat = new Zend_Db_Table('man_cat');
			if(is_array($category_id) && count($category_id) >0 ){
				foreach ($category_id as $cat_id){
					$manCat = $tblManCat->createRow();
					$manCat->man_id = $id;
					$manCat->cat_id = $cat_id;
					$manCat->save();
				}
			}else if(is_numeric($category_id)){
				$manCat = $tblManCat->createRow();
					$manCat->man_id = $id;
					$manCat->cat_id = $cat_id;
					$manCat->save();
			}
			return $id;
		}
	}
	public function updateManufacturer($id, $name, $logo, $category_id, $priority, $page_title, $page_description, $tag){
		$data = array('name' => $name, 'logo' => $logo,'priority'=>$priority, 'page_title' => $page_title, 'page_description' => $page_description, 'tag' => $tag);
		try{
		$rs = $this->update($data, 'id ='. $id);
			$this->deleteManCatByManID($id);
			$tblManCat = new Zend_Db_Table('man_cat');
			if(is_array($category_id) && count($category_id) >0 ){
				foreach ($category_id as $cat_id){
					$manCat = $tblManCat->createRow();
					$manCat->man_id = $id;
					$manCat->cat_id = $cat_id;
					$manCat->save();
				}
			}else if(is_numeric($category_id)){
				$manCat = $tblManCat->createRow();
					$manCat->man_id = $id;
					$manCat->cat_id = $cat_id;
					$manCat->save();
			}
			return true;
		
		}catch (Exception $ex){
			echo "Caught exception: " + $ex->getMessage();
			return false;
		}
	}
	public function deleteManufacturer($id){
		
		if(is_numeric($id)){
			$rs = $this->delete('id = '.$id);
		}else if(is_string($id)){
			$rs = $this->delete("id in (".$id .")");
		}
		if($rs){
			$this->deleteManCatByManID($id);
		}
		return $rs;
	}
	public function deleteManCatByManID($id){
		$tblManCat = new Zend_Db_Table('man_cat');
		if(is_numeric($id)){
			$tblManCat->delete('man_id ='. $id);
		}else if(is_string($id)){
			$tblManCat->delete("man_id in (". $id .")");
		}
	}
}